<template>
  <div class="teaching-mission-selector">
    <div class="form-item">
      <label class="form-label" :class="{ required: !isReadonly }">教学任务</label>
      <div class="mission-selection-container">
        <!-- 当前教学任务（默认选中，不可移除） -->
        <div v-if="currentMission" class="mission-item current-mission">
          <div class="mission-info">
            <div class="mission-name">{{ currentMission.courseName }}</div>
            <div class="mission-details">
              <span class="term">{{ currentMission.termName }}</span>
              <span class="teachers">
                授课教师：
                <template v-for="(teacherName, index) in currentMission.teacherNames" :key="index">
                  <span :class="{ 'primary-teacher': currentMission.teacherPrimaryFlags && currentMission.teacherPrimaryFlags[index] }">
                    {{ teacherName }}
                  </span>
                  <span v-if="index < currentMission.teacherNames.length - 1">、</span>
                </template>
              </span>
            </div>
          </div>
          <div class="mission-status">
            <el-tag type="primary" size="small">当前任务</el-tag>
          </div>
        </div>

        <!-- 当没有指定当前任务时，显示所有可选择的教学任务 -->
        <div v-if="!currentMission && availableMissions.length > 0" class="all-missions">
          <div class="section-title">{{ isReadonly ? '相关教学任务：' : '选择相关教学任务：' }}</div>
          <div class="mission-list">
            <div 
              v-for="mission in availableMissions" 
              :key="mission.id"
              class="mission-item"
              :class="{ 
                'selectable-mission': !isReadonly,
                'readonly-mission': isReadonly,
                'selected': selectedMissionIds.includes(mission.id) 
              }"
              @click="!isReadonly && toggleMissionSelection(mission)"
            >
              <div v-if="!isReadonly" class="mission-checkbox" @click.stop>
                <el-checkbox 
                  :model-value="selectedMissionIds.includes(mission.id)"
                  @change="(checked) => handleCheckboxChange(mission, checked)"
                />
              </div>
              <div class="mission-info">
                <div class="mission-name">{{ mission.courseName }}</div>
                <div class="mission-details">
                  <span class="term">{{ mission.termName }}</span>
                  <span class="teachers">
                    授课教师：
                    <template v-for="(teacherName, index) in mission.teacherNames" :key="index">
                      <span :class="{ 'primary-teacher': mission.teacherPrimaryFlags && mission.teacherPrimaryFlags[index] }">
                        {{ teacherName }}
                      </span>
                      <span v-if="index < mission.teacherNames.length - 1">、</span>
                    </template>
                  </span>
                </div>
              </div>
            </div>
          </div>
        </div>

        <!-- 其他可选择的教学任务（当有当前任务时） -->
        <div v-if="currentMission && availableMissions.length > 0" class="additional-missions">
          <div class="section-title">{{ isReadonly ? '其他相关教学任务：' : '选择其他相关教学任务：' }}</div>
          <div class="mission-list">
            <div 
              v-for="mission in availableMissions" 
              :key="mission.id"
              class="mission-item"
              :class="{ 
                'selectable-mission': !isReadonly,
                'readonly-mission': isReadonly,
                'selected': selectedMissionIds.includes(mission.id) 
              }"
              @click="!isReadonly && toggleMissionSelection(mission)"
            >
              <div v-if="!isReadonly" class="mission-checkbox" @click.stop>
                <el-checkbox 
                  :model-value="selectedMissionIds.includes(mission.id)"
                  @change="(checked) => handleCheckboxChange(mission, checked)"
                />
              </div>
              <div class="mission-info">
                <div class="mission-name">{{ mission.courseName }}</div>
                <div class="mission-details">
                  <span class="term">{{ mission.termName }}</span>
                  <span class="teachers">
                    授课教师：
                    <template v-for="(teacherName, index) in mission.teacherNames" :key="index">
                      <span :class="{ 'primary-teacher': mission.teacherPrimaryFlags && mission.teacherPrimaryFlags[index] }">
                        {{ teacherName }}
                      </span>
                      <span v-if="index < mission.teacherNames.length - 1">、</span>
                    </template>
                  </span>
                </div>
              </div>
            </div>
          </div>
        </div>

        <!-- 无可选任务时的提示 -->
        <div v-if="availableMissions.length === 0 && !loading && (!currentMission || currentMission)" class="no-additional-missions">
          <el-text type="info" size="small">
            {{ currentMission ? '暂无其他相关教学任务可选择' : '暂无相关教学任务可选择' }}
          </el-text>
        </div>

        <!-- 加载状态 -->
        <div v-if="loading" class="loading-container">
          <el-skeleton :rows="2" animated />
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, computed, watch, onMounted } from 'vue'
import { getMyTeachingMissions, getTeachingMissionsByCourseAndTerm } from '@/api/teaching-mission'
import { ElMessage } from 'element-plus'

const props = defineProps({
  currentMissionId: {
    type: [String, Number],
    required: true
  },
  courseId: {
    type: [String, Number],
    required: true
  },
  termId: {
    type: [String, Number],
    required: true
  },
  selectedMissions: {
    type: Array,
    default: () => []
  },
  isReadonly: {
    type: Boolean,
    default: false
  }
})

const emit = defineEmits(['update:selectedMissions', 'change'])

const loading = ref(false)
const currentMission = ref(null)
const availableMissions = ref([])
const selectedMissionIds = ref([])

// 初始化选中的任务ID列表
const initializeSelectedMissions = () => {
  const ids = props.selectedMissions.map(mission => 
    typeof mission === 'object' ? mission.id : mission
  )
  selectedMissionIds.value = ids.filter(id => id !== props.currentMissionId)
}

// 获取当前教学任务详情
const fetchCurrentMission = async () => {
  try {
    loading.value = true
    // 通过获取所有我的教学任务，然后过滤出当前任务
    const response = await getMyTeachingMissions({
      size: 1000 // 获取足够多的记录
    })
    
    if (response.content && response.content.length > 0) {
      const mission = response.content.find(m => m.id == props.currentMissionId)
      if (mission) {
        currentMission.value = mission
      }
    }
  } catch (error) {
    console.error('获取当前教学任务失败:', error)
    ElMessage.error('获取当前教学任务信息失败')
  }
}

// 获取相关的教学任务
const fetchAvailableMissions = async () => {
  try {
    const response = await getTeachingMissionsByCourseAndTerm({
      courseId: props.courseId,
      termId: props.termId
    })
    
    if (response) {
      if (props.currentMissionId) {
        // 有当前任务时，过滤掉当前教学任务
        availableMissions.value = response.filter(
          mission => mission.id != props.currentMissionId
        )
      } else {
        // 没有当前任务时，显示所有相关任务
        availableMissions.value = response
      }
    }
  } catch (error) {
    console.error('获取相关教学任务失败:', error)
    ElMessage.error('获取相关教学任务失败')
  } finally {
    loading.value = false
  }
}

// 切换教学任务选择状态
const toggleMissionSelection = (mission) => {
  const index = selectedMissionIds.value.indexOf(mission.id)
  if (index > -1) {
    selectedMissionIds.value.splice(index, 1)
  } else {
    selectedMissionIds.value.push(mission.id)
  }
  
  emitSelectedMissions()
}

// 处理复选框变化事件
const handleCheckboxChange = (mission, checked) => {
  const index = selectedMissionIds.value.indexOf(mission.id)
  if (checked && index === -1) {
    selectedMissionIds.value.push(mission.id)
  } else if (!checked && index > -1) {
    selectedMissionIds.value.splice(index, 1)
  }
  
  emitSelectedMissions()
}

// 发送选中的教学任务
const emitSelectedMissions = () => {
  const selectedMissions = [
    // 如果有当前教学任务则包含，否则跳过
    ...(currentMission.value ? [currentMission.value] : []),
    // 加上其他选中的教学任务
    ...availableMissions.value.filter(mission => 
      selectedMissionIds.value.includes(mission.id)
    )
  ].filter(Boolean)
  
  emit('update:selectedMissions', selectedMissions)
  emit('change', selectedMissions)
}

// 监听props变化
watch([() => props.currentMissionId, () => props.courseId, () => props.termId], 
  () => {
    if (props.courseId && props.termId) {
      // 如果有当前任务ID，获取当前任务详情
      if (props.currentMissionId) {
        fetchCurrentMission()
      }
      // 总是获取相关的教学任务
      fetchAvailableMissions()
    }
  }, 
  { immediate: true }
)

watch(() => props.selectedMissions, () => {
  initializeSelectedMissions()
}, { immediate: true, deep: true })

// 在只读模式下，确保显示所有已选择的教学任务
watch(() => props.isReadonly, (newReadonly) => {
  if (newReadonly && props.selectedMissions && props.selectedMissions.length > 0) {
    // 在只读模式下，将所有已选择的任务添加到可显示的任务列表中
    const selectedMissionIds = props.selectedMissions.map(m => m.id);
    const missingMissions = props.selectedMissions.filter(mission => 
      !availableMissions.value.some(am => am.id === mission.id) && 
      (!currentMission.value || currentMission.value.id !== mission.id)
    );
    
    if (missingMissions.length > 0) {
      availableMissions.value = [...availableMissions.value, ...missingMissions];
    }
  }
}, { immediate: true })

// 当当前任务加载完成时，发送初始选择
watch(currentMission, (newMission) => {
  if (newMission) {
    emitSelectedMissions()
  }
}, { immediate: true })

onMounted(() => {
  initializeSelectedMissions()
})
</script>

<style scoped>
.teaching-mission-selector {
  width: 100%;
}

.form-item {
  margin-bottom: 20px;
}

.form-label {
  display: block;
  margin-bottom: 8px;
  font-weight: 500;
  color: #303133;
}

.form-label.required::before {
  content: '*';
  color: #f56c6c;
  margin-right: 4px;
}

.mission-selection-container {
  border: 1px solid #dcdfe6;
  border-radius: 6px;
  padding: 16px;
  background: #fff;
}

.mission-item {
  display: flex;
  align-items: flex-start;
  padding: 12px;
  border-radius: 6px;
  margin-bottom: 12px;
  transition: all 0.3s ease;
}

.mission-item:last-child {
  margin-bottom: 0;
}

.current-mission {
  background: #f0f9ff;
  border: 1px solid #409eff;
}

.selectable-mission {
  background: #f9f9f9;
  border: 1px solid #e4e7ed;
  cursor: pointer;
}

.selectable-mission:hover {
  background: #f5f7fa;
  border-color: #c0c4cc;
}

.selectable-mission.selected {
  background: #ecf5ff;
  border-color: #409eff;
}

.readonly-mission {
  background: #f5f7fa;
  border: 1px solid #e4e7ed;
  cursor: default;
}

.readonly-mission.selected {
  background: #f0f9ff;
  border-color: #b3d8ff;
}

.mission-checkbox {
  margin-right: 12px;
  margin-top: 2px;
}

.mission-info {
  flex: 1;
}

.mission-name {
  font-size: 16px;
  font-weight: 500;
  color: #303133;
  margin-bottom: 6px;
}

.mission-details {
  font-size: 14px;
  color: #606266;
  line-height: 1.4;
}

.mission-details .term {
  display: inline-block;
  margin-right: 16px;
  font-weight: 500;
}

.mission-details .teachers {
  display: inline-block;
}

.primary-teacher {
  font-weight: 500;
  color: #409eff;
}

.mission-status {
  margin-left: 12px;
  margin-top: 2px;
}

.additional-missions {
  margin-top: 20px;
}

.section-title {
  font-size: 14px;
  font-weight: 500;
  color: #303133;
  margin-bottom: 12px;
  padding-left: 4px;
}

.mission-list {
  max-height: 300px;
  overflow-y: auto;
}

.no-additional-missions {
  text-align: center;
  padding: 20px;
  color: #909399;
}

.loading-container {
  padding: 20px;
}

/* 滚动条样式 */
.mission-list::-webkit-scrollbar {
  width: 6px;
}

.mission-list::-webkit-scrollbar-track {
  background: #f1f1f1;
  border-radius: 3px;
}

.mission-list::-webkit-scrollbar-thumb {
  background: #c0c4cc;
  border-radius: 3px;
}

.mission-list::-webkit-scrollbar-thumb:hover {
  background: #a8abb2;
}
</style>